package view.dtvb;

import java.io.File;
import java.io.FileInputStream;
import java.io.OutputStream;

import java.util.ArrayList;
import java.util.List;

import javax.faces.application.FacesMessage;
import javax.faces.context.FacesContext;

import javax.faces.event.ActionEvent;

import javax.faces.model.SelectItem;

import oracle.adf.model.binding.DCIteratorBinding;
import oracle.adf.view.rich.component.UIXTable;
import oracle.adf.view.rich.component.rich.RichPopup;
import oracle.adf.view.rich.component.rich.data.RichTable;
import oracle.adf.view.rich.component.rich.input.RichSelectOneChoice;
import oracle.adf.view.rich.component.rich.nav.RichCommandButton;
import oracle.adf.view.rich.event.DialogEvent;
import oracle.adf.view.rich.event.PopupCanceledEvent;

import oracle.jbo.Row;
import oracle.jbo.ViewCriteria;
import oracle.jbo.ViewObject;
import oracle.jbo.server.ViewRowImpl;
import oracle.jbo.uicli.binding.JUCtrlHierNodeBinding;

import org.apache.myfaces.trinidad.render.ExtendedRenderKitService;
import org.apache.myfaces.trinidad.util.Service;

import view.common.Utils;

public class noidunggopyBean {
    private UIXTable tbl;
    private String hoten;
    private String email;
    private String tieude;
    private RichPopup popupXem;
    private RichPopup popupDelete;
    private RichCommandButton buttonDownload;
    private RichSelectOneChoice selectvanban;

    public noidunggopyBean() {
        super();
        if (Boolean.FALSE.equals(Utils.getElExpression("#{adfFacesContext.postback}"))) {
            DCIteratorBinding iter1 =
                Utils.getIteratorBinding("DtvbNoidunggopyView1Iterator");
            iter1.getViewObject().getViewCriteriaManager().clearViewCriterias();
            iter1.executeQuery();
        }
    }

    public List<SelectItem> getDsvanban() {
        List<SelectItem> lstDsvanban = new ArrayList<SelectItem>();
        try {
            DCIteratorBinding iterNoidungvanban =
                Utils.getIteratorBinding("DtvbNoidungvanbanView1Iterator");

            for (Row row : iterNoidungvanban.getAllRowsInRange()) {
                lstDsvanban.add(new SelectItem(row.getAttribute("Id").toString(),
                                               row.getAttribute("TrichYeu").toString()));
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return lstDsvanban;
    }

    public void downloadfile(ActionEvent actionEvent) {
        String fileName =
            (String)actionEvent.getComponent().getAttributes().get("fileName");
        buttonDownload.setText(fileName);
        FacesContext context = FacesContext.getCurrentInstance();
        ExtendedRenderKitService erks =
            Service.getService(context.getRenderKit(),
                               ExtendedRenderKitService.class);
        erks.addScript(context, "customHandler();");
    }

    public void dwdFile(FacesContext facesContext, OutputStream out) {
        File duongdan =
            new File(Utils.ENUM_CAU_HINH_KHOA.FILE_ROOT.getValue("HtCauHinhView1Iterator"),
                     Utils.ENUM_CAU_HINH_KHOA.DTVB_DIR.getValue("HtCauHinhView1Iterator"));
        File file = new File(duongdan + "/" + buttonDownload.getText());
        FileInputStream Fileinput = null;
        byte[] bt;
        try {
            Fileinput = new FileInputStream(file);
            int checkline;
            while ((checkline = Fileinput.available()) > 0) {
                bt = new byte[checkline];
                int rst = Fileinput.read(bt);
                out.write(bt, 0, bt.length);
                if (rst == -1)
                    break;
            }
            out.flush();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void ResetSearch() {
        try {
            DCIteratorBinding iter1 =
                Utils.getIteratorBinding("DtvbNoidunggopyView1Iterator");
            iter1.getViewObject().getViewCriteriaManager().clearViewCriterias();
            iter1.executeQuery();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    
    public void searchNoidungGopy() {
        try {
            DCIteratorBinding IteratorNoidungGopy =
                Utils.getIteratorBinding("DtvbNoidunggopyView1Iterator");
            ViewObject vo = IteratorNoidungGopy.getViewObject();
            ViewCriteria vc =
                vo.getViewCriteriaManager().getViewCriteria("DtvbNoidunggopyViewCriteria");
            vo.ensureVariableManager().setVariableValue("varhoten",
                                                        getHoten());
            vo.ensureVariableManager().setVariableValue("varemail",
                                                        getEmail());
            vo.ensureVariableManager().setVariableValue("vartieude",
                                                        getTieude());
            vo.ensureVariableManager().setVariableValue("varndvanban",
                                                        selectvanban.getValue());
            vo.getViewCriteriaManager().removeViewCriteria("DtvbNoidunggopyViewCriteria");
            vo.getViewCriteriaManager().applyViewCriteria(vc);
            IteratorNoidungGopy.executeQuery();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void cancelDiaglog(PopupCanceledEvent popupCanceledEvent) {
        Utils.execute("Rollback");
    }

    public void deleteDiaglog(DialogEvent dialogEvent) {
        try {
            boolean succsess = false;
            if (Utils.getIteratorBinding("DtvbNoidunggopyView1Iterator").getCurrentRow() ==
                null) {
                String meg = "Bạn chưa chọn nội dung góp ý nào.";
                Utils.showMessage(Utils.MSG_INFO, meg);
            } else {
                DCIteratorBinding iterNoidunggopy =
                    Utils.getIteratorBinding("DtvbNoidunggopyView1Iterator");
                if (tbl.getSelectedRowKeys().size() > 0) {
                    for (Object facesRowKey : tbl.getSelectedRowKeys()) {
                        tbl.setRowKey(facesRowKey);
                        Object objrow = tbl.getRowData();
                        if (objrow == null) {
                            succsess = true;
                        } else {
                            JUCtrlHierNodeBinding rowData =
                                (JUCtrlHierNodeBinding)objrow;
                            Row row = rowData.getRow();
                            if (row.getAttribute("FileId") != null) {
                                DCIteratorBinding iterHtFile =
                                    Utils.getIteratorBinding("HtFileView1Iterator");
                                File filePath =
                                    new File(Utils.ENUM_CAU_HINH_KHOA.FILE_ROOT.getValue("HtCauHinhView1Iterator"),
                                             "/");
                                String FileId =
                                    row.getAttribute("FileId").toString();
                                iterHtFile.setCurrentRowWithKeyValue(FileId);
                                String duongdan =
                                    iterHtFile.getCurrentRow().getAttribute("DuongDan").toString();
                                File oldPath = new File(filePath, duongdan);
                                Utils.fileDelete(oldPath);
                                // Xoa trong bang Ht_File
                                iterHtFile.removeCurrentRow();
                            }
                            ViewRowImpl viewRow = (ViewRowImpl)row;
                            String key =
                                viewRow.getKey().toStringFormat(false);
                            iterNoidunggopy.removeRowWithKey(key);
                        }

                    }
                    if (succsess) {
                        String meg = "Bạn chưa chọn bản ghi nào";
                        Utils.showMessage(Utils.MSG_INFO, meg);
                    }
                    Utils.execute("Commit");
                } else {
                    String messg = "Bạn chưa chọn bản ghi nào.";
                    Utils.showMessage(Utils.MSG_INFO, messg);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void openPopupDelete(ActionEvent actionEvent) {
        if (Utils.getIteratorBinding("DtvbNoidunggopyView1Iterator").getCurrentRow() ==
            null) {
            String messageText = "Không có nội dung góp ý nào.";
            Utils.showMessage(Utils.MSG_INFO, messageText);
        } else {
            Utils.showPopup(popupDelete);
        }
    }
    
    public void setTbl(UIXTable tbl) {
        this.tbl = tbl;
    }

    public UIXTable getTbl() {
        return tbl;
    }

    public void setHoten(String hoten) {
        this.hoten = hoten;
    }

    public String getHoten() {
        return hoten;
    }

    public void setEmail(String email) {
        this.email = email;
    }

    public String getEmail() {
        return email;
    }

    public void setTieude(String tieude) {
        this.tieude = tieude;
    }

    public String getTieude() {
        return tieude;
    }

    public void setButtonDownload(RichCommandButton buttonDownload) {
        this.buttonDownload = buttonDownload;
    }

    public RichCommandButton getButtonDownload() {
        return buttonDownload;
    }

    public void setSelectvanban(RichSelectOneChoice selectvanban) {
        this.selectvanban = selectvanban;
    }

    public RichSelectOneChoice getSelectvanban() {
        return selectvanban;
    }

    public void setPopupXem(RichPopup popupXem) {
        this.popupXem = popupXem;
    }

    public RichPopup getPopupXem() {
        return popupXem;
    }

    public void setPopupDelete(RichPopup popupDelete) {
        this.popupDelete = popupDelete;
    }

    public RichPopup getPopupDelete() {
        return popupDelete;
    }
}
